<?php 
if(!defined('IN_ALWU')){
	exit('Access Denied');
}
class common{
	function saddslashes($string){
		if(is_array($string)){
			foreach($string as $key => $val){
				$string[$key] = $this->saddslashes($val);
			}
		}else{
			$string = addslashes($string);
		}
		return $string;
	}
	
	function ckfounder($uid){
		global $_SCF;
		$founders = empty($_SCF['web']['founder'])?array():explode(',', $_SCF['web']['founder']);
		if($uid && $founders){
			return in_array($uid, $founders);
		}else{
			return false;
		}
	}

	function shtmlspecialchars($string){
		if(is_array($string)){
			foreach($string as $key => $val){
				$string[$key] = $this->shtmlspecialchars($val);
			}
		}else{
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
				                   str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string)
								   );
		}
		return $string;
	}
	
	function getonlineip($format=0) {
		global $SGLOBAL;
		if(empty($SGLOBAL['onlineip'])) {
			if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
				$onlineip = getenv('HTTP_CLIENT_IP');
			} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
				$onlineip = getenv('HTTP_X_FORWARDED_FOR');
			} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
				$onlineip = getenv('REMOTE_ADDR');
			} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
				$onlineip = $_SERVER['REMOTE_ADDR'];
			}
			preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
			$SGLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
		}
		if($format) {
			$ips = explode('.', $SGLOBAL['onlineip']);
			for($i=0;$i<3;$i++) {
				$ips[$i] = intval($ips[$i]);
			}
			return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
		} else {
			return $SGLOBAL['onlineip'];
		}
	}

		
	
	function xml_out($content) {
		global $_SCF;
		@header("Expires: -1");
		@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
		@header("Pragma: no-cache");
		@header("Content-type: application/xml; charset={$_SCF[db][charset]}");
		echo '<'."?xml version=\"1.0\" encoding=\"{$_SCF[db][charset]}\"?>\n";
		echo "<root><![CDATA[".trim($content)."]]></root>";
		exit();
	}
	
	function debuginfo() {
		global $SGLOBAL, $_SCF;
		if(!D_BUG){
			$info = '';
		}else{
			$mtime = explode(' ', microtime());
			$totaltime = number_format(($mtime[1] + $mtime[0] - $SGLOBAL['supe_starttime']), 4);
			$info = 'Processed in '.$totaltime.' second(s), MySql in '.$SGLOBAL['db']->querynum.' queries'.
					($_SCF['web']['gzipcompress'] ? ', Gzip enabled' : NULL);
		}
		return $info;
	}
	
	
	function clearcookie() {
		global $SGLOBAL;
		foreach($_COOKIE as $key => $value){
			$this->ssetcookie($key, '', -86400 * 365);
		}
		$SGLOBAL['uid'] = 0;
		$SGLOBAL['user'] = '';
		$SGLOBAL['member'] = array();
	}
	
	function ssetcookie($var, $value, $life=0) {
		global $SGLOBAL, $_SCF, $_SERVER;
		setcookie($_SCF['cookie']['pre'].$var, $value, $life?($SGLOBAL['timestamp']+$life):0, $_SCF['cookie']['path'], $_SCF['cookie']['domain'], $_SERVER['SERVER_PORT']==443?1:0);
	}
	
	function getcookie($var) {
		global $_SCF;
		return $_COOKIE[$_SCF['cookie']['pre'].$var];
	}	
	
	function lang($nid){
		global $SGLOBAL,$_SCF,$_LANG;
		if(empty($SGLOBAL['lang'])){
			$lang = $_SCF['web']['lang'];
			include_once S_ROOT.'language/'.$lang.'/lang.php';
			$SGLOBAL['lang'] = $lang;
		}
		return $_LANG[$nid];
	}
	
	function sgmdate($dateformat, $timestamp='', $format=0){
		global $_SCF, $SGLOBAL;
		if(empty($timestamp)){
			$timestamp = $SGLOBAL['timestamp'];
		}
		$timeoffset = strlen($_SCF['web']['timeoffset'])>0?intval($_SCF['web']['timeoffset']):intval(8);
		$result = '';
		if($format){
			$time = $SGLOBAL['timestamp'] - $timestamp;
			if($time > 24*3600) {
				$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
			} elseif ($time > 3600) {
				$result = intval($time/3600).$this->lang('hour').$this->lang('before');
			} elseif ($time > 60) {
				$result = intval($time/60).$this->lang('minute').$this->lang('before');
			} elseif ($time > 0) {
				$result = $time.$this->lang('second').$this->lang('before');
			} else {
				$result = $this->lang('now');
			}
		} else {
			$result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
		}
		return $result;
	}
	
	function _htaccess($Arr){
		$Str = '<FilesMatch (.*)\.([htm|php|asp|aspx]*)$>'."\r\n".'order allow,deny'."\r\n".'deny from all'."\r\n".'</FilesMatch>';
		foreach($Arr as $key => $value){
			file_put_contents(S_ROOT.$value.'/.htaccess',$Str);
		}
	}
	
	function NewFileFolder($path){
	   if (!file_exists($path)){
		  $this->NewFileFolder(dirname($path));
		  @mkdir($path,0777);
	  }
	}
	
	function cache_write($name, $var, $values){
		global $SGLOBAL,$_SCF;
		$cachefile = $_SCF['db']['dbcache'].$SGLOBAL['sen']->set('lang').'/'.$name.'.php';
		$this->NewFileFolder(dirname($cachefile));
		$cachetext = "<?php\r\n".
			"if(!defined('IN_ALWU')) exit('Access Denied');\r\n".
			'$SGLOBAL[\''.$var.'\']='.$this->arrayeval($values).
			"\r\n?>";
		if(!$this->swritefile($cachefile, $cachetext)){
			exit("File: $cachefile write error.");
		}
	}
	
	function swritefile($filename, $writetext, $openmod='w'){
		if(@$fp = fopen($filename, $openmod)){
			flock($fp, 2);
			fwrite($fp, $writetext);
			fclose($fp);
			return true;
		}else{
			$this->runlog('error', "File: $filename write error.");
			return false;
		}
	}
	
	function deltreedir($dir){
		$files = $this->sreaddir($dir);
		foreach ($files as $file){
			if(is_dir("$dir/$file")){
				$this->deltreedir("$dir/$file");
			} else {
				@unlink("$dir/$file");
			}
		}
	}
	
	function fileext($filename){
		return strtolower(trim(substr(strrchr($filename, '.'), 1)));
	}
	
	function sreaddir($dir, $extarr=array()) {
		$dirs = array();
		if($dh = opendir($dir)){
			while (($file = readdir($dh)) !== false) {
				if(!empty($extarr) && is_array($extarr)) {
					if(in_array(strtolower($this->fileext($file)), $extarr)) {
						$dirs[] = $file;
					}
				} else if($file != '.' && $file != '..') {
					$dirs[] = $file;
				}
			}
			closedir($dh);
		}
		return $dirs;
	}

	function strexists($haystack, $needle){
		return !(strpos($haystack, $needle) === FALSE);
	}

	
	function arrayeval($array, $level = 0){
		if(!is_array($array)){
			return '\''.addcslashes($array, '\'\\').'\';';
		}
		$space = '';
		for($i = 0; $i <= $level; $i++) {
			$space .= "\t";
		}
		$evaluate = "Array\n$space(\n";
		$comma = $space;
		foreach($array as $key => $val) {
			$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
			$val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12 || substr($val, 0, 1)=='0') ? '\''.addcslashes($val, '\'\\').'\'' : $val;
			if(is_array($val)) {
				$evaluate .= "$comma$key => ".$this->arrayeval($val, $level + 1);
			} else {
				$evaluate .= "$comma$key => $val";
			}
			$comma = ",\n$space";
		}
		$evaluate .= "\n$space)";
		return $evaluate;
	}
	
	function runlog($file, $log, $halt=0){
		global $SGLOBAL, $_SERVER, $_SCF;
	
		$nowurl = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
		$log = $this->sgmdate('Y-m-d H:i:s', $SGLOBAL['timestamp'])."\t$type\t".$this->getonlineip()."\t$_SGLOBAL[uid]\t{$nowurl}\t".str_replace(array("\r", "\n"), array(' ', ' '), trim($log))."\n";
		$yearmonth = $this->sgmdate('Ymd', $SGLOBAL['timestamp']);
		$logdir = $_SCF['db']['errorlog'];
		if(!is_dir($logdir)) mkdir($logdir, 0777);
		$logfile = $logdir.$yearmonth.'____'.$file.'.php';
		if(@filesize($logfile) > 2048000) {
			$dir = opendir($logdir);
			$length = strlen($file);
			$maxid = $id = 0;
			while($entry = readdir($dir)) {
				if($this->strexists($entry, $yearmonth.'_'.$file)) {
					$id = intval(substr($entry, $length + 8, -4));
					$id > $maxid && $maxid = $id;
				}
			}
			closedir($dir);
			$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
			@rename($logfile, $logfilebak);
		}
		if($fp = @fopen($logfile, 'a')) {
			@flock($fp, 2);
			fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>', "\r", "\n"), '', $log)."\n");
			fclose($fp);
		}
		if($halt) exit();
	}

	
	function getstr($string, $length=80, $etc='...', $html=0, $charset='utf-8') {
		$string = trim($string);
		if($html > 0) {
			//去掉html标签
			$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
			$string = $this->shtmlspecialchars($string);
		}else{
			//转换html标签
			$string = $this->shtmlspecialchars($string);
		}
	
		if($length && strlen($string) > $length) {
			//截断字符
			$wordscut = '';
			if(strtolower($charset) == 'utf-8') {
				//utf8编码
				$n = 0;
				$tn = 0;
				$noc = 0;
				while ($n < strlen($string)) {
					$t = ord($string[$n]);
					if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
						$tn = 1;
						$n++;
						$noc++;
					} elseif(194 <= $t && $t <= 223) {
						$tn = 2;
						$n += 2;
						$noc += 2;
					} elseif(224 <= $t && $t < 239) {
						$tn = 3;
						$n += 3;
						$noc += 2;
					} elseif(240 <= $t && $t <= 247) {
						$tn = 4;
						$n += 4;
						$noc += 2;
					} elseif(248 <= $t && $t <= 251) {
						$tn = 5;
						$n += 5;
						$noc += 2;
					} elseif($t == 252 || $t == 253) {
						$tn = 6;
						$n += 6;
						$noc += 2;
					} else {
						$n++;
					}
					if ($noc >= $length) {
						break;
					}
				}
				if ($noc > $length) {
					$n -= $tn;
				}
				$wordscut = substr($string, 0, $n);
			} else {
				for($i = 0; $i < $length - 1; $i++) {
					if(ord($string[$i]) > 127) {
						$wordscut .= $string[$i].$string[$i + 1];
						$i++;
					} else {
						$wordscut .= $string[$i];
					}
				}
			}
			$string = $wordscut.$etc;
		}
	
		return trim($string);
	}
	
		
	function sendmail($toemail, $subject, $message, $from='', $mailType='text/html') {
		global $_SCF;
		$mail = $_SCF['mail'];
		$mail['auth']     = $mail['auth_username'];
		$maildelimiter    = $mail['maildelimiter'] == 1 ? "\r\n" : ($mail['maildelimiter'] == 2 ? "\r" : "\n");
		$mailusername     = $mail['mailusername'];
		$mail['port']     = $mail['port'] ? $mail['port'] : 25;
		$mail['mailsend'] = $mail['mailsend'] ? $mail['mailsend'] : 1;
		
		$email_from = $from == '' ? '=?'.$_SCF['db']['charset'].'?B?'.base64_encode($mail['mailusername'])."?= <".$mail['adminemail'].">" : (preg_match('/^(.+?) \<(.+?)\>$/',$from, $mats) ? '=?'.$_SCF['db']['charset'].'?B?'.base64_encode($mats[1])."?=<$mats[2]>" : $from);
		
		$email_to = preg_match('/^(.+?) \<(.+?)\>$/',$toemail, $mats) ? ($mailusername ? '=?'.$_SCF['db']['charset'].'?B?'.base64_encode($mats[1])."?= <$mats[2]>" : $mats[2]) : $toemail;
		
		//$email_subject = '=?'.$_SCF['db']['charset'].'?B?'.base64_encode(preg_replace("/[\r|\n]/", '', '['.$_SCF['web']['domain'].'] '.$subject)).'?=';
		$email_subject = '=?'.$_SCF['db']['charset'].'?B?'.base64_encode(preg_replace("/[\r|\n]/", '', $subject)).'?=';
		$email_message = chunk_split(base64_encode(str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $message))))));
		
		$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: ALWUTECH ".X_VER."{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: {$mailType}; charset={$_SCF['db']['charset']}{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";
		
		if(!$fp = @fsockopen($mail['server'], $mail['port'], $errno, $errstr, 30)) {
			$this->runlog('SMTP', "($mail[server]:$mail[port]) CONNECT - Unable to connect to the SMTP server", 0);
			return -2;
		}
		
		stream_set_blocking($fp, true);
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != '220') {
			$this->runlog('SMTP', "$mail[server]:$mail[port] CONNECT - $lastmessage", 0);
			return -3;
		}
		
		fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." SJMP5\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
			$this->runlog('SMTP', "($mail[server]:$mail[port]) HELO/EHLO - $lastmessage", 0);
			return -4;
		}
		
		while(1) {
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
				break;
			}
			$lastmessage = fgets($fp, 512);
		}
		
		if($mail['auth']) {
			fputs($fp, "AUTH LOGIN\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				$this->runlog('SMTP', "($mail[server]:$mail[port]) AUTH LOGIN - $lastmessage", 0);
				return -5;
			}
			
			fputs($fp, base64_encode($mail['auth_username'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				$this->runlog('SMTP', "($mail[server]:$mail[port]) USERNAME - $lastmessage", 0);
				return -6;
			}
			
			fputs($fp, base64_encode($mail['auth_password'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 235) {
				$this->runlog('SMTP', "($mail[server]:$mail[port]) PASSWORD - $lastmessage", 0);
				return -7;
			}
			$email_from = $mail['auth_username'];
		}
		
		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 250) {
			$this->runlog('SMTP', "($mail[server]:$mail[port]) MAIL FROM - $lastmessage", 0);
			return -8;
			}
		}
		
		fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail).">\r\n");
			$lastmessage = fgets($fp, 512);
			$this->runlog('SMTP', "($mail[server]:$mail[port]) RCPT TO - $lastmessage", 0);
			return -9;
		}
		
		fputs($fp, "DATA\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 354) {
			$this->runlog('SMTP', "($mail[server]:$mail[port]) DATA - $lastmessage", 0);
			return -10;
		}
		
		$headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";
		$headers .= "The-Author: ye guo zheng";
		fputs($fp, "Date: ".gmdate('r')."\r\n");
		fputs($fp, "To: ".$email_to."\r\n");
		fputs($fp, "Subject: ".$email_subject."\r\n");
		fputs($fp, $headers."\r\n");
		fputs($fp, "\r\n\r\n");
		fputs($fp, "$email_message\r\n.\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			$this->runlog('SMTP', "($mail[server]:$mail[port]) END - $lastmessage", 0);
			return -11;
		}
		fputs($fp, "QUIT\r\n");
		return true;
	}

	
	
}
$_SCF['web']['domain']         = 'http://www.sjmp5.com/';
$_SCF['db']['charset']         = 'utf-8';
$_SCF['mail']['mailusername']  = 'adying';
$_SCF['mail']['auth_username'] = 'sjmp5@qq.com';
$_SCF['mail']['auth_password'] = '************';
$_SCF['mail']['adminemail']    = 'sjmp5@qq.com';
$_SCF['mail']['server']        = 'smtp.qq.com';
$_SCF['mail']['port']          = 25;
$aaa = $SGLOBAL['common']->sendmail('176341052@qq.com', '信的测试标题', '这里是信的内容');
var_dump($aaa);
